package com.lzy.handle;

import com.lzy.common.R;
import com.lzy.enums.ExceptionEnums;
import com.lzy.exception.AlreadyExistException;
import com.lzy.exception.ServiceException;
import com.lzy.exception.authority.PermissionNotAllowedException;
import com.lzy.exception.user.JwtExpiredException;
import com.lzy.exception.user.SessionTimeoutException;
import com.lzy.exception.user.UserException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lyw
 * @Date 2023/2/14-下午5:49
 */
@RestControllerAdvice
public class GlobalDefaultExceptionHandler {

  @ResponseBody
  @ExceptionHandler({SessionTimeoutException.class, JwtExpiredException.class, MalformedJwtException.class, ExpiredJwtException.class})
  public R sessionTimeout(RuntimeException e) {
    e.printStackTrace();
    return R.error(ExceptionEnums.SESSION_TIMEOUT.getCode(), ExceptionEnums.SESSION_TIMEOUT.getMessage());
  }

  @ResponseBody
  @ExceptionHandler(PermissionNotAllowedException.class)
  public R permissionException(PermissionNotAllowedException e) {
    e.printStackTrace();
    return R.error(ExceptionEnums.NOT_PERMISSION.getCode(), ExceptionEnums.NOT_PERMISSION.getMessage());
  }

  @ResponseBody
  @ExceptionHandler(UserException.class)
  public R userException(UserException e) {
    e.printStackTrace();
    return R.error(e.getCode(), e.getMessage());
  }

  @ResponseBody
  @ExceptionHandler(ServiceException.class)
  public R serviceException(ServiceException e) {
    e.printStackTrace();
    return R.error(e.getCode(), e.getMessage());
  }

  @ResponseBody
  @ExceptionHandler(AlreadyExistException.class)
  public R alreadyExistsException(AlreadyExistException e) {
    e.printStackTrace();
    return R.error(e.getCode(), e.getMessage());
  }

  @ResponseBody
  @ExceptionHandler(Exception.class)
  public R globalException(Exception e) {
    e.printStackTrace();
    return R.error(500, "系统异常！");
  }
}
